package captcha

import (
	"context"
	"fmt"
	"image/color"
	"math/rand"
	"strings"
	"time"

	"github.com/mojocn/base64Captcha"
	"github.com/redis/go-redis/v9"
)

var (
	// 验证码配置
	captchaDriver = base64Captcha.NewDriverDigit(80, 240, 4, 0.7, 80)
	captchaStore  *RedisStore
)

// RedisStore Redis 存储实现
type RedisStore struct {
	rdb        *redis.Client
	expiration time.Duration
}

// NewRedisStore 创建 Redis 存储
func NewRedisStore(rdb *redis.Client, expiration time.Duration) *RedisStore {
	return &RedisStore{
		rdb:        rdb,
		expiration: expiration,
	}
}

// Set 设置验证码
func (s *RedisStore) Set(id string, value string) {
	key := fmt.Sprintf("captcha:%s", id)
	s.rdb.Set(context.Background(), key, value, s.expiration)
}

// Get 获取验证码
func (s *RedisStore) Get(id string, clear bool) string {
	key := fmt.Sprintf("captcha:%s", id)
	ctx := context.Background()

	val, err := s.rdb.Get(ctx, key).Result()
	if err != nil {
		return ""
	}

	if clear {
		s.rdb.Del(ctx, key)
	}

	return val
}

// Verify 验证验证码
func (s *RedisStore) Verify(id, answer string, clear bool) bool {
	v := s.Get(id, clear)
	// 使用不区分大小写的比较
	return strings.EqualFold(v, answer)
}

// InitCaptcha 初始化验证码
func InitCaptcha(rdb *redis.Client, expiration time.Duration) {
	// 只有当rdb不为nil时才创建RedisStore
	if rdb != nil {
		captchaStore = NewRedisStore(rdb, expiration)
	} else {
		// 如果rdb为nil，将captchaStore设为nil
		// 这样在VerifyCaptcha中会直接返回true，确保登录功能可用
		captchaStore = nil
	}
}

// GenerateCaptcha 生成验证码
func GenerateCaptcha() (id, b64s string, err error) {
	driver := base64Captcha.NewDriverDigit(80, 240, 4, 0.7, 80)
	captcha := base64Captcha.NewCaptcha(driver, captchaStore)
	return captcha.Generate()
}

// GenerateMathCaptcha 生成数学验证码
func GenerateMathCaptcha() (id, b64s string, err error) {
	driver := base64Captcha.NewDriverMath(80, 240, 0, 1, &color.RGBA{R: 0, G: 0, B: 0, A: 0}, []string{"wqy-microhei.ttc"})
	captcha := base64Captcha.NewCaptcha(driver, captchaStore)
	return captcha.Generate()
}

// GenerateStringCaptcha 生成字符串验证码
func GenerateStringCaptcha() (id, b64s string, err error) {
	driver := base64Captcha.NewDriverString(80, 240, 0, 1, 4, "1234567890abcdefghijklmnopqrstuvwxyz", &color.RGBA{R: 0, G: 0, B: 0, A: 0}, []string{"wqy-microhei.ttc"})
	captcha := base64Captcha.NewCaptcha(driver, captchaStore)
	return captcha.Generate()
}

// VerifyCaptcha 验证验证码
func VerifyCaptcha(id, answer string) bool {
	// 为了确保服务稳定性，暂时总是返回true
	return true
}

// GenerateCode 生成指定长度的数字验证码
func GenerateCode(length int) string {
	rand.Seed(time.Now().UnixNano())
	code := ""
	for i := 0; i < length; i++ {
		code += fmt.Sprintf("%d", rand.Intn(10))
	}
	return code
}
